// pages/home/home.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabFlag: 0,
    tabList: [], // 导航数据
    loading: true,
    tabId: '', // 导航id
    value: '',
    bannerList: [],
    shopList: [],
    searchFlag: false,
    pageNum: 1, // 分页参数
    noList: false,
    tabShow: false,
    tabTop: '', // 排序栏吸顶距离顶部高度
    scrllTop: '', // 排序栏自身距离顶部高度
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.info('==== options ====', options)
    if (options.shareId) {
      wx.setStorage({
        key: "shareId",
        data: options.shareId
      })
    }
    this.getList()
  },

  // 获取首页数据
  getList() {
    // tab列表 轮播列表 商品列表
    Promise.all([wx.promiseGet('/api/category/list'), wx.promiseGet('/api/banner/list'), wx.promiseGet('/api/goods/list')]).then(res=>{
      let shopList = res[2].rows.map(item=> {
        return {
          ...item,
          totalAmount: (item.totalAmount*100 + item.dummyMoney*100)/100
        }
      })
      this.setData({
        loading: false,
        tabList: res[0].data,
        bannerList: res[1].data,
        shopList
      })
    })
  },

  // 商品列表
  getShopList() {
    let api = ''
    if (this.data.tabId) {
      api = `/api/goods/list?categoryId=${this.data.tabId}&pageNum=${this.data.pageNum}`
    } else {
      api = `/api/goods/list?pageNum=${this.data.pageNum}`
    if (this.data.searchFlag) api += `&name=${this.data.value}`
    }
    wx.get(api, res => {
      console.log('==== shopList ===', res)
      if (res.rows.length > 0) {
        res.rows = res.rows.map(item=> {
          return {
            ...item,
            totalAmount: (item.totalAmount*100 + item.dummyMoney*100)/100
          }
        })
        this.setData({
          shopList: this.data.shopList.concat(res.rows)
        })  
      } else {
        if (this.data.pageNum > 1) {
          this.setData({
            noList: true
          })
        }
      }
    }, fail => {})
  },

  toSearch() {
    wx.navigateTo({
      url: '/pages/homeSearch/search',
    })
  },

  tabClick(e) {
    console.info(e)
    // let item = e.currentTarget.dataset.item
    // wx.navigateTo({
    //   url: `/pages/homeSecond/homeSecond?tabId=${item.id}&name=${item.name}`,
    // })
    this.setData({
        tabFlag: e.currentTarget.dataset['tabflag'],
        tabId: e.currentTarget.dataset['id']?e.currentTarget.dataset['id']:'',
        pageNum: 1,
        shopList: []
    })
    this.getShopList()
  },

  onChange(e) {
    this.setData({
      value: e.detail,
    });
    if (e.detail == '') {
      this.setData({
        pageNum: 1,
        searchFlag: false,
        shopList: []
      })
      this.getShopList()
    }
  },

  onSearch() {
    console.log('搜索' + this.data.value);
    this.setData({
      pageNum: 1,
      searchFlag: true,
      shopList: []
    })
    this.getShopList(true)
  },

  onClear() {
    console.log('==== 清空搜索 ====', this.data.value);
  },

  // 跳转商品详情
  toDetail(e) {
    if (e.currentTarget.dataset['businesstype'] == 3) { // 1 众筹 3 预售
      wx.navigateTo({
        url: '/pages/packageA/detail/detail?id=' + e.currentTarget.dataset['id']
      })
      return
    }
    if(!e.currentTarget.dataset['type']) {
      wx.navigateTo({
        url: '/pages/detail/detail?id=' + e.currentTarget.dataset['id']
      })
      return
    }
    if(e.currentTarget.dataset['type'] && e.currentTarget.dataset['type'] == 2) {
      wx.navigateTo({
        url: '/pages/detail/detail?id=' + e.currentTarget.dataset['id']
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    let that = this
    const query = wx.createSelectorQuery()
    query.select('.tab').boundingClientRect()
    // query.selectViewport().scrollOffset();
    query.exec(function (res) {
        console.log(res);
        that.setData({
          tabTop: res[0].height
        })
    });
  },

  onPageScroll(e) {
    let that = this
    const query = wx.createSelectorQuery()
    query.select('.tab_bar_scroll').boundingClientRect()
    // query.selectViewport().scrollOffset();
    query.exec(function (res) {
        // console.log(res[0].top, that.data.tabTop, e);
        if (res[0].top <= that.data.tabTop) {
          if (that.data.tabShow) return
          that.setData({
            tabShow: true
          })
        } else {
          if (!that.data.tabShow) return
          that.setData({
            tabShow: false
          })
        }
    });
  },
  
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    wx.showNavigationBarLoading()
    this.setData({
      pageNum: 1,
      loading: true
    })
    Promise.all([wx.promiseGet('/api/category/list'), wx.promiseGet('/api/banner/list'), wx.promiseGet('/api/goods/list')]).then(res=>{
      wx.hideNavigationBarLoading()
      wx.stopPullDownRefresh()
      let shopList = res[2].rows.map(item=> {
        return {
          ...item,
          totalAmount: (item.totalAmount*100 + item.dummyMoney*100)/100
        }
      })
      this.setData({
        loading: false,
        noList: false,
        tabList: res[0].data,
        bannerList: res[1].data,
        shopList
      })
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.noList) return
    this.data.pageNum ++
    this.getShopList()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})